package main

import (
	"fmt"
	"io"
	"net"
	"sync"
	"time"
)

type Server struct {
	Ip   string
	Port int
	// record online users
	// protect from data race
	OnlineMap map[string]*User // userName -> User
	mapLock   sync.RWMutex     // read > write

	// broadcast chanel
	Message chan string
}

// create a server
func NewServer(ip string, port int) *Server {
	return &Server{
		Ip:        ip,
		Port:      port,
		OnlineMap: make(map[string]*User),
		Message:   make(chan string),
	}
}

// goroutine: listen server message chanel, send message to online users
func (this *Server) ListenMessage() {
	for {
		msg := <-this.Message
		// send to all users online
		// remember to lock
		this.mapLock.Lock()
		for _, user := range this.OnlineMap {
			user.C <- msg
		}
		this.mapLock.Unlock()
	}
}

func (this *Server) Broadcast(user *User, msg string) {
	// format a message
	sendMsg := "[" + user.Addr + "]" + user.Name + " : " + msg

	this.Message <- sendMsg
}

func (this *Server) Handler(conn net.Conn) {
	// create user
	user := NewUser(conn, this)

	// user online
	user.Online()

	// chanel for user's activity
	isLive := make(chan bool)

	// receive users' message
	go func() {
		buf := make([]byte, 4096)
		for {
			n, err := conn.Read(buf)
			if n == 0 {
				user.Offline()
				return
			}
			if err != nil && err != io.EOF {
				fmt.Println("conn read err:", err)
				return
			}
			// get msg
			msg := string(buf[:n-1])
			// handle msg
			user.DoMessage(msg)
			// update avtivity
			isLive <- true
		}
	}()

	// block current handler
	for {
		select {
		case <-isLive:
			// user is live
		case <-time.After(time.Second * 300):
			// user is OUTTIME
			// kick user out
			user.SendMsg("you have been kicked!\n")
			close(user.C)
			conn.Close()
			return // runtime.Goexit()
		}
	}
}

// start a server
func (this *Server) Start() {
	// socket listen
	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", this.Ip, this.Port))
	if err != nil {
		fmt.Println("net.listen err:", err)
		return
	}
	fmt.Println("server is listening on port:",this.Port)
	defer listener.Close()

	// start listen message chanel
	go this.ListenMessage()

	// wait for clients
	for {
		// accept
		connect, err := listener.Accept()
		if err != nil {
			fmt.Println("listener accept err:", err)
			continue
		}
		// do handler
		go this.Handler(connect)

	}

	// close socket(defer to here)
}
